package labuladong.第三章.滑动窗口;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Demo03 {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("abcabcbb");
        list.add("bbbb");
        list.add("pwwkew");

        for(String s : list) {
            System.out.println(longestStr(s));
        }
    }

    public static int longestStr(String s) {
        int right = 0, left = 0;
        int res = 0;

        char[] sArr = s.toCharArray();
        Map<Character, Integer> window = new HashMap<>();

        while (right < s.length()) {
            char c1 = sArr[right];
            window.put(c1, window.getOrDefault(c1, 0) + 1);
            right++;
            while (window.get(c1) > 1) {
                char c2 = sArr[left];
                if (window.get(c2) == 1) {
                    window.remove(c2);
                } else {
                    window.put(c2, window.get(c2)-1);
                }
                left++;
            }
            res = Math.max(res, right-left);
        }
        return res;
    }
}
